﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PointAsLine
{
    public class Line
    {
        public double K { get; set; } // 斜率
        public double B { get; set; } // 截距

        public Line(double k, double b)
        {
            K = k;
            B = b;
        }

        public override string ToString()
        {
            return $"y = {K}x + {B}";
        }

        // 最小二乘法拟合直线 y = a*x + b
        public void FitLineLeastSquares(List<PointF2G> points)
        {
            int n = points.Count;
            if (n < 2)
            {
                throw new ArgumentException("At least two points are required to fit a line");
            }

            float sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;

            foreach (var p in points)
            {
                sumX += p.X;
                sumY += p.Y;
                sumXY += p.X * p.Y;
                sumXX += p.X * p.X;
            }

            // 计算斜率a和截距b
            float denominator = n * sumXX - sumX * sumX;

            // 处理垂直线情况 (分母为零)
            if (Math.Abs(denominator) < 1e-6f)
            {
                // 垂直线，斜率无限大，我们返回一个极大值表示
                K = float.PositiveInfinity;
                B = 0;
                return ;
            }

            float a = (n * sumXY - sumX * sumY) / denominator;
            float b = (sumY - a * sumX) / n;

            K = a;
            B = b;
        }

        public double ComputeR(PointF2G point)
        {
            // 特殊情况处理：垂直线 (斜率无限大)
            bool isVertical = double.IsInfinity(K);

            float r;
            if (isVertical)
            {
                // 垂直线，使用y坐标作为投影参数
                r = point.Y;
            }
            else
            {
                // 计算投影参数r (沿直线方向的距离)
                // 对于直线 y = a*x + b，我们使用x坐标作为基础
                r = (float)((point.X + K* (point.Y - B)) / (1 + K * K));
            }
            return r;
        }
    }
}
